package com.zmn.oms.business.impl.messageV1.text;

import com.alibaba.fastjson.JSON;
import com.zmn.base.common.data.common.query.tags.TagsQuery;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.shortlink.common.enums.shortlink.ShortLinkTypeEnum;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.mcc.common.dto.organize.OrganizeDRO;
import com.zmn.mcc.dubbo.interfaces.organize.OrganizeListRemoteService;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.oms.business.interfaces.messageV1.common.MessageSendBaseService;
import com.zmn.oms.business.interfaces.messageV1.text.MessageSendTextService;
import com.zmn.oms.common.constant.MessageConsts;
import com.zmn.oms.common.constant.MessageRuleIdConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.model.dto.messageV1.SendMessageParams;
import com.zmn.oms.model.dto.messageV1.ShortUrlDTO;
import com.zmn.oms.model.dto.messageV1.SmsMessageDTO;
import com.zmn.oms.model.dto.messageV1.TextMessageDTO;
import com.zmn.oms.model.entity.advancequote.AdvanceQuoteOpenQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.work.OrderWork;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：
 *
 * @author yule
 * @date 2020/12/23 14:24
 */
@Service
@Slf4j
public class MessageSendTextServiceImpl extends AbstractMessageSendText implements MessageSendTextService {
    private Logger logger = LoggerFactory.getLogger(MessageSendTextServiceImpl.class);

    @Autowired
    private MessageSendBaseService messageSendBaseService;
    @Autowired
    private BaseCodeService baseCodeService;

    @DubboReference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private OrganizeListRemoteService organizeListRemoteService;

    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public boolean sendTextMessage(Integer ruleId, String mobile) {
        return sendTextMessage(ruleId, mobile, null);
    }

    @Override
    public boolean sendTextMessage(Integer ruleId, String mobile, Map<String, String> params) {
        return messageSendBaseService.sendTextMessage(ruleId, mobile, params);
    }

    @Override
    public boolean sendTextMessage(TextMessageDTO textMessageDTO) {
        SmsMessageDTO smsMessageDTO = BeanMapper.map(textMessageDTO, SmsMessageDTO.class);
        return messageSendBaseService.sendTextMessage(smsMessageDTO);
    }

    @Override
    public boolean sendTextMessage(SendMessageParams param) {
        OrderWork orderWork = param.getOrderWork();
        // 参数处理
        Map<String, String> smsMap = super.handleSendParams(param);

        if (smsMap == null) {
            return false;
        }

        Integer ruleId = param.getRuleId();
        Integer customerConfirmQuotedRuleId = this.getCustomerConfirmQuotedRuleId(param, orderWork, smsMap);
        if (Objects.nonNull(customerConfirmQuotedRuleId)) {
            ruleId = customerConfirmQuotedRuleId;
        }

        SmsMessageDTO smsMessageDTO = SmsMessageDTO.builder()
                .orderId(param.getOrderId())
                .businessId(param.getOrderId())
                .mobile(param.getSendPhone())
                .ruleId(ruleId)
                .params(JSON.toJSONString(smsMap))
                .channelId(String.valueOf(orderWork.getChannelId()))
                .cityId(String.valueOf(orderWork.getCityId()))
                .build();
        return messageSendBaseService.sendTextMessage(smsMessageDTO);
    }

    /**
     * 下单报价信息判断
     * 服务地址：江西南昌
     * 下单渠道：全部渠道
     * 服务产品：家电维修 - **维修（产品待定）
     *
     * @param params
     * @param orderWork
     * @param smsMap
     * @return
     */
    private Integer getCustomerConfirmQuotedRuleId(SendMessageParams params, OrderWork orderWork, Map<String, String> smsMap) {
        // 只有短信特殊处理， 微信消息还是使用默认的场景
        boolean isConfirmOrder = Objects.equals(MessageRuleIdConsts.ZMN_MSG_RULEID_ASSIGN, params.getRuleId()) ||
                Objects.equals(MessageRuleIdConsts.ZMN_MSG_RULEID_ASSIGN_NO_LOGIN, params.getRuleId());
        if (!isConfirmOrder) {
            return null;
        }

        // 判断试点  江西南昌 下单报价判断
        AdvanceQuoteOpenQuery advanceQuoteOpenQuery = AdvanceQuoteOpenQuery.builder()
                .cityId(orderWork.getCityId())
                .servCategId(orderWork.getServCategId())
                .showProductType(NumberUtil.isNotNullOrZero(orderWork.getProductId()) ? BaseProductConsts.ERP_SHOW_TYPE : BaseProductConsts.EC_SHOW_TYPE)
                .productId(NumberUtil.isNotNullOrZero(orderWork.getProductId()) ? orderWork.getProductId() : orderWork.getShowProductId())
                .build();
        boolean openAdvanceQuote = baseCodeService.isOpenAdvanceQuote(advanceQuoteOpenQuery);
        if (!openAdvanceQuote) {
            return null;
        }

        // 南昌 用户端 - 下单成功通知
        // 您的{$product_name}已预约，我们将{$contact_time}第一时间联系您{$Prompt_content} d.zmn.cn/{$short_link}
        // params.setRuleId(MessageConsts.ZMN_MSG_RULEID_CUSTOMER_CONFIRM_QUOTED);

        // 订单已确认服务价格
        if (NumberUtil.isNotNullOrZero(orderWork.getTotalAmount())) {
            smsMap.put("prompt_content", String.format("。服务费用预计%s，点击查看服务内容及费用说明 ", MoneyUtil.parseToYuanStr(orderWork.getTotalAmount())));
        } else {
            smsMap.put("prompt_content", "确认服务费用，请注意接听来电。点击查看服务进度 ");
        }

        ShortUrlDTO shortUrlDTO = ShortUrlDTO.builder()
                .orderId(params.getWorkId())
                .ruleId(params.getRuleId())
                .shortLinkType(ShortLinkTypeEnum.MINIPROGRAMS_SHORTLINK.getKey())
                .miniProgramsLink(String.format(productDetailWechatQuotation3Url, orderWork.getShowProductId()))
                .build();
        smsMap.put("short_link", messageGetSendInfoService.getShortUrl(shortUrlDTO));

        return MessageConsts.ZMN_MSG_RULEID_CUSTOMER_CONFIRM_QUOTED;
    }

    @Override
    public boolean sendVipTextMessage(OrderWork orderWork, OrderDetail orderDetail) {
        // 线上环境才发送
        if (!Objects.equals(active, "prod")) {
            return false;
        }
        String companyName = orderWork.getCompanyName();
        Integer companyId = orderWork.getCompanyId();
        String receiveTime = DateUtil.dateFormatToString(orderWork.getReceiveTime(), "yyyy年MM月dd日HH时mm分");

        ResponseDTO<OrganizeDRO> companyResponseDTO = organizeListRemoteService.getByCompanyId(companyId);
        if (companyResponseDTO.getData() == null) {
            log.error("[{}]Remote接口未找到公司", orderWork.getCompanyId());
            return false;
        }
        logger.info("要客#OrganizeListRemoteService#getByCompanyId：[{}]", com.github.ltsopensource.core.json.JSON.toJSONString(companyResponseDTO));
        OrganizeDRO organizeDRO = companyResponseDTO.getData();
        // 发送电话
        String vipPhone = organizeDRO.getManagerPhone();
        if (StringUtils.isBlank(vipPhone)) {
            log.error("[{}]Remote接口未找到公司负责人电话", orderWork.getCompanyId());
            return false;
        }
        // 获取姓名即可
        String vipName = StringUtils.isBlank(organizeDRO.getManagerName()) ? "" : organizeDRO.getManagerName().substring(0, 1);
        // 测试环境
       /* if (!Objects.equals(active, "prod")) {
            vipPhone = "19922290223";
            vipName = "刘";
        }
        */
        Map<String, String> smsMap = new HashMap();
        smsMap.put("order_id", String.valueOf(orderWork.getOrderId()));
        smsMap.put("order_time", receiveTime);
        smsMap.put("user_name", orderDetail.getUserName());
        smsMap.put("user_telephone", orderDetail.getTelephone());
        smsMap.put("company_name", companyName);
        smsMap.put("city_name", orderDetail.getCityName());
        smsMap.put("vip_name", vipName);
        return messageSendBaseService.sendTextMessage(MessageRuleIdConsts.ZMN_MSG_RULEID_VVIP, vipPhone, smsMap);
    }

}
